package com.tanhua.manage.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.manage.constant.Constant;
import com.tanhua.manage.exception.BusinessException;
import com.tanhua.manage.mapper.AdminMapper;
import com.tanhua.model.db.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    // 用户登录
    public Map login(String username, String password, String verificationCode, String uuid) {


        // 从redis中获取验证码
        String code = redisTemplate.opsForValue().get(Constant.CHECK_CODE + uuid);

        // 判断验证码是否正确
        if (!verificationCode.equals(code)) {

            // 不正确则抛出异常
            throw new BusinessException("验证码错误");
        }

        // 验证码正确则删除缓存数据
        redisTemplate.delete(Constant.CHECK_CODE + uuid);

        // 判断用户名和密码
        // 1.根据用户名查询用户
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Admin admin = adminMapper.selectOne(queryWrapper);

        // 2.进行加密
        password = SecureUtil.md5(password);

        // 3.进行判断
        if (admin == null || !password.equals(admin.getPassword())) {

            // 不正确则抛出异常
            throw new BusinessException("用户名或密码错误");
        }

        // 生成token
        Map map = new HashMap();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        String token = JwtUtils.getToken(map);

        // 构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);

        return retMap;
    }
}
